import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { LayoutComponent } from "../../../global/layout/layout.component";
import { YclService } from "./ycl.service";
import * as moment from 'moment';
import * as _ from 'lodash';
import { Validators, FormGroup, FormControl } from '@angular/forms';
import { environment } from '../../../../../environments/environment';
import { AppPaginationComponent, PaginationModel } from "../../../../widgets/pagination/pagination.component";
import * as flatpickr from 'flatpickr';
import { DataService } from '../../../../services/data.service';
import { zh } from "flatpickr/dist/l10n/zh.js";
import { Util } from 'app/common/util';

@Component({
  selector: 'app-ycl',
  templateUrl: './ycl.component.html',
  styleUrls: ['./ycl.component.scss'],
  providers: [YclService]
})
export class YclComponent implements OnInit {
  // lodash
  public _: any = _;
  // 字典值
  public dictionaryList: any = {
    STOP_TYPE: []
  };
  // 备案机构、受托人、托管人
  public distionary: any = {
    RECORDORG_TYPE: [],  // 备案机构
    LINK_PRINCIPAL_NO: [],   //受托人
    TRUSTEE: []   //  托管人
  }
  // 菜单数据
  public menuData: any;
  // 菜单按钮集合
  //  托管人数据
  // public bankDictionaryList = [];

  public menuResourceSet: any;
  // 菜单按钮集合
  // 产品业务类型,修改(1)、续约(2)、终止(3)、开始运作(4)
  public businessType: any;
  // 一对多单个产品信息
  public otmProductBody: any = {};
  //查询分页列表post数据
  public getOnetomanyPost = {
    pageIndex: 1,
    pageSize: 10,
    sFullName: '',
    sFundCode: '',
    sFundStatus: 2,
    sStatusRunning: '',
    sTrustee: ''
  };
  //一对多分页配置
  public onetomanyListPageInfo: PaginationModel = {
    currentPageNum: 1,
    pageSize: 10,
    totalPages: 1,
    total: 0,
    pagesShow: 5,
    startRow: 0,
    endRow: 0,
    pageList: [5, 10, 25, 50, 100]
  };
  //一对多分页列表list
  public onetomanyList = [];
  // 列表是否全选
  public isCheckedAll: boolean = false;
  // 用于续约/终止录入对比有无修改
  public checkBody: any;
  constructor(
    public router: Router,
    public layoutComponent: LayoutComponent,
    public yclService: YclService,
    public dataservice: DataService
  ) {
    this.list();
  }

  ngOnInit() {
    let that = this;
    // 初始化日期控件
    flatpickr.localize(zh);
    // 字典值
    this.dictionaryList = JSON.parse(localStorage.getItem("dictionaryList"));
    sessionStorage.setItem('otm_isStop', 'isnoStop');
    // 权限处理
    this.dataservice.initTree.subscribe((data) => {
      let SessionMenuData = sessionStorage.getItem('menu');
      this.menuData = JSON.parse(SessionMenuData)
      this.menuResourceSet = [];
      _.forEach(this.menuData, (item, index) => {
        if (item.sName == '一对多专户') {
          _.forEach(item.children, (it, idx) => {
            if (it.sName == '已成立') {
              that.menuResourceSet = it.resourceSet
              sessionStorage.setItem('btn-otm', that.menuResourceSet);
            }
          })
        }
      })
    })
    let SessionMenuData = sessionStorage.getItem('menu');
    this.menuData = JSON.parse(SessionMenuData)
    this.menuResourceSet = [];
    _.forEach(this.menuData, (item, index) => {
      if (item.sName == '一对多专户') {
        _.forEach(item.children, (it, idx) => {
          if (it.sName == '已成立') {
            that.menuResourceSet = it.resourceSet
            sessionStorage.setItem('btn-otm', that.menuResourceSet);
          }
        })
      }
    })
    this.getDictionary();
    // 获取托管人数据
    // this.bankDictionaryList = JSON.parse(localStorage.getItem("bankDictionaryList"));
  }
  // 一对多分页
  list(pageNum?, pageSize?) {
    let that = this;
    this.isCheckedAll = false;
    this.getOnetomanyPost.sFullName = _.trim(this.getOnetomanyPost.sFullName);
    this.getOnetomanyPost.sFundCode = _.trim(this.getOnetomanyPost.sFundCode);
    this.getOnetomanyPost.sTrustee = _.trim(this.getOnetomanyPost.sTrustee);
    this.getOnetomanyPost.pageIndex = pageNum ? pageNum : this.onetomanyListPageInfo.currentPageNum;
    this.getOnetomanyPost.pageSize = pageSize ? pageSize : this.onetomanyListPageInfo.pageSize;
    this.yclService.list(this.getOnetomanyPost).subscribe(data => {
      if (data) {
        that.onetomanyList = data.list;
        that.onetomanyListPageInfo.currentPageNum = data.pageNum;
        that.onetomanyListPageInfo.totalPages = data.pages;
        that.onetomanyListPageInfo.total = data.total;
        that.onetomanyListPageInfo.startRow = data.startRow;
        that.onetomanyListPageInfo.endRow = data.endRow;
      }
      // // 给表格列支持列拖动效果
      // setTimeout(() => {
      //   Util.colResizable("#fixed-table");
      // }, 100);

      // 给表格列支持列拖动和固定表头效果
      Util.colResizable("#yclList");
    });
  }
  // 个数分页
  onetomanypageSizeChange(pageSize: number) {
    if (pageSize !== this.onetomanyListPageInfo.pageSize) {
      this.onetomanyListPageInfo.pageSize = pageSize;
      this.list();
    }
  }
  // 页码分页
  onetomanyPageNavigation(currentPageNum: number) {
    this.onetomanyListPageInfo.currentPageNum = currentPageNum;
    this.list(this.onetomanyListPageInfo.currentPageNum, this.onetomanyListPageInfo.pageSize);
  }
  // 列表全选
  checkedAll() {
    if (this.isCheckedAll) { // 更新为全选
      _.forEach(this.onetomanyList, item => {
        item.isChecked = true;
      });
    } else { // 更新为不全选
      _.forEach(this.onetomanyList, item => {
        item.isChecked = false;
      });
    }
  }
  // 列表是否全选
  ctrlCheckAll() {
    let that = this;
    let checkList = [];
    _.forEach(this.onetomanyList, item => {
      if (item.isChecked == true) {
        checkList.push(item);
      }
    })
    if (checkList.length == this.onetomanyList.length) {
      this.isCheckedAll = true;
    } else {
      this.isCheckedAll = false;
    }
  }
  // 导出
  exportExcel() {
    let that = this;
    let checkedItem = [];
    _.forEach(that.onetomanyList, item => {
      if (item.isChecked == true) {
        checkedItem.push(item.nFundNo);
      }
    })
    let converItem = checkedItem.join(',');
    let getBody = {
      "nFundNoList": converItem,
      "sFundStatus": this.getOnetomanyPost.sFundStatus,
      "sFullName": this.getOnetomanyPost.sFullName,
      "sFundCode": this.getOnetomanyPost.sFundCode,
      "sStatusRunning": this.getOnetomanyPost.sStatusRunning,
      "sTrustee": this.getOnetomanyPost.sTrustee
    }
    getBody.sFullName = encodeURI(getBody.sFullName)
    getBody.sTrustee = encodeURI(getBody.sTrustee)
    getBody.sFundCode = encodeURI(getBody.sFundCode)
    const iframe = window['$']("<iframe id='downloadiframe'>");
    iframe.attr('style', 'display:none');
    iframe.attr('src', environment.server + '/pms/v1/onetomany/export/oneToManyFundInfoList?token=' + sessionStorage.getItem('token') + '&nFundNoList=' + getBody.nFundNoList + '&sFundStatus=' + getBody.sFundStatus + '&sFullName=' + getBody.sFullName + '&sFundCode=' + getBody.sFundCode + '&sStatusRunning=' + getBody.sStatusRunning + '&sTrustee=' + getBody.sTrustee);
    window['$']('body').append(iframe);
    setTimeout("$('#downloadiframe').remove()", 60000);
  }
  edit(type, item?) {
    let that = this;
    sessionStorage.setItem('parentIndex', 'ycl');
    // 产品修改勾选
    let checkProduct = [];
    switch (type) {
      case 'dbclick':
        sessionStorage.setItem('currentTitle', "详情·已成立·一对多");
        that.layoutComponent.nav(null, null, "详情·已成立·一对多");
        that.router.navigate(['pages/onetomany/ycl/detail/edit/' + item.nFundNo]);
        break;
      case 'one':
        _.forEach(that.onetomanyList, it => {
          if (it.isChecked == true) {
            checkProduct.push(it);
          }
        })
        if (checkProduct.length == 1) {
          sessionStorage.setItem('currentTitle', "详情·已成立·一对多");
          that.layoutComponent.nav(null, null, "详情·已成立·一对多");
          that.router.navigate(['pages/onetomany/ycl/detail/edit/' + checkProduct[0].nFundNo]);
        } else {
          window['swal']("提示", "请选择一个产品进行查看", "warning");
        }
        break;
    }
  }

  // 续约按钮
  goRenew() {
    let that = this;
    let checkProduct = [];
    this.otmProductBody = {};
    _.forEach(this.onetomanyList, item => {
      if (item.isChecked == true) {
        checkProduct.push(item);
      }
    })
    if (checkProduct.length == 1) {
      this.businessType = "2";
      this.yclService.checkProductStatus(checkProduct[0].nFundNo, this.businessType).subscribe(data => {
        if (data == true) {
          window['swal']("提示", "该产品正在续约审核中...", "warning");
        } else {
          that.yclService.otmGetSingleProduct(checkProduct[0].nFundNo).subscribe(data => {
            if (data) {
              that.otmProductBody = data;
              // 用于续约/终止录入时对比
              that.checkBody = _.clone(data);
              window['$']("#renewProduct").modal('show');
            }
          })
        }
      })
    } else {
      window['swal']("提示", "请选择一个产品进行续约", "warning")
    }
  }
  // 产品续约
  productRenew() {
    let that = this;
    // 产品业务类型,修改(1)、续约(2)、终止(3)、开始运作(4)
    this.businessType = "2";
    // 必填校验
    if (this.requiredRenew()) {
      // 判断数据有无修改
      if (Util.objectCheck(that.checkBody, that.otmProductBody)) {
        window['swal']("提示", "信息未修改，不会生成修改审核记录", "warning");
        window['$']("#renewProduct").modal('hide');
      } else {
        window["swal"]({
          title: "提示",
          text: "是否确定续约操作?",
          type: "warning",
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          showCancelButton: true,
          closeOnConfirm: false,
          closeOnCancel: true,
          showLoaderOnConfirm: true
        },
          function (isConfirm) {
            if (isConfirm) {
              delete that.otmProductBody.sTrusteeZh;
              delete that.otmProductBody.sFundCategoryZh;
              delete that.otmProductBody.sSalesChannels;
              delete that.otmProductBody.nValueDecZh;
              delete that.otmProductBody.sIsHandZh;
              that.yclService.operationType(that.otmProductBody, that.businessType).subscribe(data => {
                if (data) {
                  window['swal']("成功", "请等待产品审核!", "success");
                  window['$']("#renewProduct").modal('hide');
                }
              })
            }
          })
      }
    }
  }
  // 续约必填校验
  requiredRenew() {
    let that = this;
    if (this.otmProductBody.dEnd == "" || this.otmProductBody.dEnd == null) {
      window['swal']("提示", "请填写: 新的到期日", "warning");
      return false;
    } else {
      return true;
    }
  }
  // 产品续约到期日重置
  resetEndDate() {
    this.otmProductBody.dEnd = "";
  }
  // 终止按钮
  goStop() {
    let that = this;
    // 终止勾选产品
    let checkProduct = [];
    this.otmProductBody = {};
    _.forEach(this.onetomanyList, item => {
      if (item.isChecked == true) {
        checkProduct.push(item);
      }
    })
    if (checkProduct.length == 1) {
      this.businessType = "3";
      this.yclService.checkProductStatus(checkProduct[0].nFundNo, this.businessType).subscribe(data => {
        if (data == true) {
          window['swal']("提示", "该产品正在终止审核中...", "warning");
        } else {
          that.yclService.otmGetSingleProduct(checkProduct[0].nFundNo).subscribe(data => {
            if (data) {
              that.otmProductBody = data;
              // 用于续约/终止录入时对比
              that.checkBody = _.clone(data);
              window['$']("#stopProduct").modal('show');
            }
          })
        }
      })
    } else {
      window['swal']("提示", "请选择一个产品进行终止", "warning")
    }
  }
  // 产品终止
  productStop() {
    let that = this;
    // 产品业务类型,修改(1)、续约(2)、终止(3)、开始运作(4)
    this.businessType = "3";
    // 必填校验
    if (this.requiredStop()) {
      // 判断数据有无修改
      if (Util.objectCheck(that.checkBody, that.otmProductBody)) {
        window['swal']("提示", "信息未修改，不会生成修改审核记录", "warning");
        window['$']("#stopProduct").modal('hide');
      } else {
        window["swal"]({
          title: "提示",
          text: "是否确定终止操作?",
          type: "warning",
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          showCancelButton: true,
          closeOnConfirm: false,
          closeOnCancel: true,
          showLoaderOnConfirm: true
        },
          function (isConfirm) {
            if (isConfirm) {
              delete that.otmProductBody.sTrusteeZh;
              delete that.otmProductBody.sFundCategoryZh;
              delete that.otmProductBody.sSalesChannels;
              delete that.otmProductBody.nValueDecZh;
              delete that.otmProductBody.sIsHandZh;
              that.yclService.operationType(that.otmProductBody, that.businessType).subscribe(data => {
                if (data) {
                  window['swal']("成功", "请等待产品审核!", "success");
                  window['$']("#stopProduct").modal('hide');
                }
              })
            }
          })
      }
    }
  }
  // 终止必填校验
  requiredStop() {
    let that = this;
    let requiredStopTip = [];
    if (this.otmProductBody.dStop == "" || this.otmProductBody.dStop == null) {
      requiredStopTip.push("终止日期");
    }
    if (this.otmProductBody.sStopType == "" || this.otmProductBody.sStopType == null) {
      requiredStopTip.push("终止方式");
    }
    if (requiredStopTip.length > 0) {
      let requiredStopTips = requiredStopTip.join("、");
      window['swal']("提示", "请填写:" + requiredStopTips, "warning");
      return false;
    } else {
      return true;
    }
  }
  // 产品终止信息重置
  resetStop() {
    this.otmProductBody.dStop = "";
    this.otmProductBody.sStopType = "";
    this.otmProductBody.sStopReason = "";
  }

  // 计算合同到期日
  countMonth() {
    if (this.otmProductBody.dBegin && this.otmProductBody.nContractPeriod) {
      this.otmProductBody.dEnd = moment(this.otmProductBody.dBegin).add(this.otmProductBody.nContractPeriod, 'months').format('YYYY-MM-DD')
    } else {
      this.otmProductBody.dEnd = '';
    }
  }
  // 点击表格头排序
  orderData(colName) {
    let listDataAsc = _.orderBy(this.onetomanyList, [colName], ["asc"]);
    if (JSON.stringify(this.onetomanyList) == JSON.stringify(listDataAsc)) {
      listDataAsc = _.orderBy(this.onetomanyList, [colName], ["desc"]);
    }
    this.onetomanyList = listDataAsc;
  }
  // 获取备案机构、受托人、托管人下拉框值
  getDictionary() {
    let that = this;
    this.yclService.getDictionary().subscribe(data => {
      if (data) {
        that.distionary.RECORDORG_TYPE = data.RECORDORG_TYPE;
        that.distionary.LINK_PRINCIPAL_NO = data.LINK_PRINCIPAL_NO;
        that.distionary.TRUSTEE = data.TRUSTEE;
      }
    })
  }
  ngAfterViewInit() {
    let that = this;
    // 多选下拉框
    window['$'](".select2").select2();
    window['$']('#sTrusteeSelected').select2({ width: '182px', tags: true });
    window['$']('#sTrusteeSelected').on("select2:select", function (e) {
      that.getOnetomanyPost.sTrustee = window['$']('#sTrusteeSelected').select2("val");
    })
  }
}
